﻿/**
 * Created by asus on 2019/7/20.
 */
var express = require("express")
var User = require("./models/user")
var Share = require("./models/share")
var Question = require("./models/question")
var Recruitment = require("./models/recruitment")
var md5 = require('blueimp-md5')
const formidable = require('formidable');
const path = require('path');
var router = express.Router()
var Time = {
    // 获取当前时间戳
    getUnix: function () {
        var date = new Date();
        return date.getTime();
    },

    // 获取今天 0 点 0 分 0 秒的时间戳
    getTodayUnix: function () {
        var date = new Date();
        date.setHours(0);
        date.setMinutes(0);
        date.setSeconds(0);
        date.setMilliseconds(0);
        return date.getTime();
    },

    // 获取今年 1月 1 日 0 点 0 分 0 秒的时间戳
    getYearUnix: function () {
        var date = new Date();
        date.setMonth(0);
        date.setDate(1);
        date.setHours(0);
        date.setMinutes(0);
        date.setSeconds(0);
        date.setMilliseconds(0);
        return date.getTime();
    },

    // 获取标准年月日
    getLastDate: function (time) {
        var date = new Date(time);
        var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
        var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
        return date.getFullYear() + '-' + month + '-' + day;
    },

    // 转换时间
    getFormatTime: function (timestamp) {
        var now = this.getUnix();
        var today = this.getTodayUnix();
        var year = this.getYearUnix();
        var timer = (now - timestamp) / 1000;
        var tip = "";

        if (timer <= 0) {
            tip = "刚刚";
        } else if (Math.floor(timer / 60) <= 0) {
            tip = "刚刚";
        } else if (timer < 3600) {
            tip = Math.floor(timer / 60) + "分钟前";
        } else if (timer >= 3600 && (timestamp - today >= 0)) {
            tip = Math.floor(timer / 3600) + "小时前";
        } else if (timer / 84600 <= 31) {
            tip = Math.ceil(timer / 86400) + "天前";
        } else {
            tip = this.getLastDate(timestamp);
        }

        return tip;
    }
}
router.get("/", function (req, res) {

    res.redirect("/share")
})
router.get("/share", function (req, res, next) {
    if (req.query.id) {
        req.query.id = req.query.id.slice(1, -1)
        Share.findOneAndUpdate({ _id: req.query.id }, { $inc: { browse: 1 } }, function (err, doc) {
            if (err) return next(err)
            doc.time = Time.getFormatTime(doc.created_time)
            doc.last = Time.getFormatTime(doc.last_modified_time)
            doc.comments = doc.comments.reverse()
            doc.comments.forEach(item => {
                item.time = Time.getFormatTime(item.time)
            })

            res.render("topic/show.html", {
                user: req.session.user,
                data: doc,
                type: "share",
                id: req.query.id,
                share: 'active',
                question: '',
                recruitment: ''
            })
        })

        return
    }

    Share.find(null, null, null, function (err, docs) {
        if (err) {
            return next(err)
        }
        docs.forEach((item) => {

            item.time = Time.getFormatTime(item.created_time)

        })

        res.render("index.html", {
            user: req.session.user,
            data: docs.reverse(),
            share: 'active',
            question: '',
            recruitment: ''

        })
    })
})


router.post("/share", function (req, res, next) {
    if (!req.session.user) {
        res.json({
            err_code: 400
        })
        return;
    }
    var body = {};
    body.name = req.session.user.nickname
    body.content = req.body.content
    body.time = Date.now()
    Share.findOneAndUpdate({ _id: req.body.id }, { $addToSet: { comments: [body] } }, function (err, doc) {
        if (err) return next(err)
        body.time2 = Time.getFormatTime(body.time)
        res.jsonp(body)
    })
})


router.post("/question", function (req, res, next) {
    if (!req.session.user) {
        res.json({
            err_code: 400
        })
        return;
    }
    var body = {};
    body.name = req.session.user.nickname
    body.content = req.body.content
    body.time = Date.now()
    Question.findOneAndUpdate({ _id: req.body.id }, { $addToSet: { comments: [body] } }, function (err, doc) {
        if (err) return next(err)
        body.time2 = Time.getFormatTime(body.time)
        res.jsonp(body)
    })
})


router.post("/recruitment", function (req, res, next) {
    if (!req.session.user) {
        res.json({
            err_code: 400
        })
        return;
    }
    var body = {};
    body.name = req.session.user.nickname
    body.content = req.body.content
    body.time = Date.now()
    Recruitment.findOneAndUpdate({ _id: req.body.id }, { $addToSet: { comments: [body] } }, function (err, doc) {
        if (err) return next(err)
        body.time2 = Time.getFormatTime(body.time)
        res.jsonp(body)
    })
})


router.get("/question", function (req, res, next) {
    if (req.query.id) {
        req.query.id = req.query.id.slice(1, -1)
        Question.findOneAndUpdate({ _id: req.query.id }, { $inc: { browse: 1 } }, function (err, doc) {
            if (err) return next(err)
            doc.time = Time.getFormatTime(doc.created_time)
            doc.last = Time.getFormatTime(doc.last_modified_time)

            doc.comments = doc.comments.reverse()
            doc.comments.forEach(item => {
                item.time = Time.getFormatTime(item.time)
            })
            res.render("topic/show.html", {
                user: req.session.user,
                data: doc,
                type: "question",
                share: '',
                question: 'active',
                recruitment: '',
                id: req.query.id
            })
        })
        return
    }
    Question.find(null, null, null, function (err, docs) {
        if (err) {
            return next(err)
        }
        docs.forEach((item) => {

            item.time = Time.getFormatTime(item.created_time)

        })

        res.render("index.html", {
            user: req.session.user,
            data: docs.reverse(),
            type: 'question',
            share: '',
            question: 'active',
            recruitment: ''

        })
    })

})
router.get("/recruitment", function (req, res, next) {
    if (req.query.id) {
        req.query.id = req.query.id.slice(1, -1)
        Recruitment.findOneAndUpdate({ _id: req.query.id }, { $inc: { browse: 1 } }, function (err, doc) {
            if (err) return next(err)
            doc.time = Time.getFormatTime(doc.created_time)
            doc.last = Time.getFormatTime(doc.last_modified_time)
            doc.comments = doc.comments.reverse()
            doc.comments.forEach(item => {
                item.time = Time.getFormatTime(item.time)
            })
            res.render("topic/show.html", {
                user: req.session.user,
                data: doc,
                type: "recruitment",
                share: '',
                question: '',
                recruitment: 'active',
                id: req.query.id
            })
        })
        return
    }
    Recruitment.find(null, null, null, function (err, docs) {
        if (err) {
            return next(err)
        }
        docs.forEach((item) => {

            item.time = Time.getFormatTime(item.created_time)

        })
        res.render("index.html", {
            user: req.session.user,
            data: docs.reverse(),
            share: '',
            question: '',
            recruitment: 'active'

        })
    })

})
router.get("/login", function (req, res) {
    res.render("login.html")
})
router.post("/login", function (req, res, next) {
    var body = req.body
    User.findOne({
        email: body.email,
        password: md5(md5(body.password))
    },
        function (err, user) {
            if (err) {
                return next(err)
            }
            if (!user) {
                return res.status(200).json({
                    err_code: 1,
                    message: 'Email or password is invalid.'
                })
            }
            req.session.user = user
            res.status(200).json({
                err_code: 0,
                message: "OK"
            })
        }
    )
})
router.get('/register', function (req, res, next) {
    res.render('register.html')
})

router.post('/register', function (req, res, next) {
    // 1. 获取表单提交的数据
    //    req.body
    // 2. 操作数据库
    //    判断改用户是否存在
    //    如果已存在，不允许注册
    //    如果不存在，注册新建用户
    // 3. 发送响应
    var body = req.body
    User.findOne({
        $or: [{
            email: body.email
        },
        {
            nickname: body.nickname
        }
        ]
    }, function (err, data) {
        if (err) {
            // return res.status(500).json({
            //   success: false,
            //   message: '服务端错误'
            // })
            return next(err)
        }
        // console.log(data)
        if (data) {
            // 邮箱或者昵称已存在
            return res.status(200).json({
                err_code: 1,
                message: 'Email or nickname aleady exists.'
            })
            return res.send(`邮箱或者密码已存在，请重试`)
        }

        // 对密码进行 md5 重复加密
        body.password = md5(md5(body.password))

        new User(body).save(function (err, user) {
            if (err) {
                return next(err)
            }

            // 注册成功，使用 Session 记录用户的登陆状态
            req.session.user = user

            // Express 提供了一个响应方法：json
            // 该方法接收一个对象作为参数，它会自动帮你把对象转为字符串再发送给浏览器
            res.status(200).json({
                err_code: 0,
                message: 'OK'
            })

            // 服务端重定向只针对同步请求才有效，异步请求无效
            // res.redirect('/')
        })
    })
})
router.get("/logout", function (req, res) {
    req.session.user = null;
    res.redirect("/login")
})
router.get("/topics/new", function (req, res) {
    res.render("topic/new.html", {
        user: req.session.user
    })
})
router.post("/topics/new", function (req, res, next) {
    if (!req.session.user) {
        return res.json({
            err_code: 400
        })
    }
    var body = req.body;
    body.browse = 0;
    body.comments = [];
    body.author = req.session.user.nickname;
    body.avatar = req.session.user.avatar;
    switch (body.type) {
        case "share":
            new Share(body).save(function (err, res) {
                if (err) {
                    return next(err)
                }

            }); break;
        case "question":
            new Question(body).save(function (err, res) {
                if (err) {
                    return next(err)
                }

            }); break;
        case "recruitment":
            new Recruitment(body).save(function (err, res) {
                if (err) {
                    return next(err)
                }

            }); break;
    }
    res.json({
        err_code: 200
    })
})


router.post("/topics/edit", function (req, res, next) {
    if (!req.session.user) {
        return res.json({
            err_code: 400
        })
    }
    var body = req.body;
   
    switch (body.type) {
        case "share":
            Share.findByIdAndUpdate(body.id,{title:body.title,content:body.content},function (err,doc){
                if(err) return next(err)
            })
            break;
        case "question":
            Question.findByIdAndUpdate(body.id,{title:body.title,content:body.content},function (err,doc){
                if(err) return next(err)
            }); break;
        case "recruitment":
            Recruitment.findByIdAndUpdate(body.id,{title:body.title,content:body.content},function (err,doc){
                if(err) return next(err)
            }); break;
    }
    res.json({
        err_code: 200
    })
})
//设置页面
router.get("/settings/admin", function (req, res) {
    if (!req.session.user) {
        return res.send("请先登录")
    }
    res.render("settings/admin.html", {
        a: "",
        b: "active",
        c: "",
        user: req.session.user
    })
})
router.get("/settings/profile", function (req, res) {
    if (!req.session.user) {
        return res.send("请先登录")
    }
    res.render("settings/profile.html", {
        a: "active",
        b: "",
        c: "",
        user: req.session.user
    })
})
router.get("/settings/avatar", function (req, res) {
    if (!req.session.user) {
        return res.send("请先登录")
    }
    res.render("settings/avatar.html", {
        a: "",
        b: "",
        c: "active",
        user: req.session.user
    })
})
router.get("/myinfo", function (req, res) {
    if (!req.session.user) {
        return res.send("请先登录")
    }
    res.render("settings/myinfo.html", {

        user: req.session.user
    })
})
router.post("/profile", function (req, res, next) {
    Share.updateMany(null,{ author:req.body.nickName }, 
        function (err, doc) {
            if (err) return next(err)
          
        })
    Question.updateMany(null,{ author:req.body.nickName  },
        function (err, doc) {
            if (err) return next(err)
           
        })
    Recruitment.updateMany(null,{ author:req.body.nickName  },
        function (err, doc) {
            if (err) return next(err)
           
        })
    User.findOneAndUpdate({ email: req.session.user.email }, {
        birthday: req.body.birthday,
        bio: req.body.introduce,
        nickname: req.body.nickName,
        gender: req.body.sex
    }, function (err, doc) {
        if (err) return next(err)
        req.session.user = null;
        res.render("success.html")

    })
})
//密码修改
router.post("/admin",function(req,res,next){
    var oldpassword = md5(md5(req.body.olds));
    var newpassword = md5(md5(req.body.news));;
    User.findOneAndUpdate({password:oldpassword,email:req.session.user.email},{password:newpassword},
          function (err,doc){
              if(err) return next(err)
              res.send("修改密码成功")
          })
})
//头像修改
router.post('/upload', (req, res, next) => {
    if (!req.session.user) return res.send("请先登录")
    var form = new formidable.IncomingForm();
    //为了能更好的保存文件在本地服务器目录
    form.uploadDir = path.join(__dirname, 'files');
    //是否保留后缀名
    form.keepExtensions = true;
    //解析请求
    form.parse(req, function (err, fields, files) {
        if (err) {
            console.log("出错了")
            return next(err);
        }
        console.log('上传文件完毕')
        //保存头像路径至数据库
        console.log(files)
        var imgpath = "/files/" + path.basename(files.myFile.path)
        User.findOneAndUpdate({ email: req.session.user.email }, { avatar: imgpath },
            function (err, doc) {
                if (err) return next(err)
                
            })
        Share.updateMany({ author:req.session.user.nickname }, { avatar: imgpath },
            function (err, doc) {
                if (err) return next(err)
              
            })
        Question.updateMany({ author:req.session.user.nickname  }, { avatar: imgpath },
            function (err, doc) {
                if (err) return next(err)
               
            })
        Recruitment.updateMany({ author:req.session.user.nickname  }, { avatar: imgpath },
            function (err, doc) {
                if (err) return next(err)
                res.send("上传成功")
            })

    });
})
//搜索页面
router.get("/search", function (req, res, next) {
    var searchKey = req.query.searchKey;
    var key = new RegExp(searchKey);
    var rest = []
    Share.find({
        $or: [{ 'content': key },
        { 'title': key }
        ]
    }).then(function (docs) {
        rest = rest.concat(docs)
        return Question.find({
            $or: [{ 'content': key },
            { 'title': key }
            ]
        })
    }).then(function (docs) {
        rest = rest.concat(docs)
        return Recruitment.find({
            $or: [{ 'content': key },
            { 'title': key }
            ]
        })
    }).then(function (docs) {
        rest = rest.concat(docs)
        res.render("index.html", {
            user: req.session.user,
            data: rest,
            share: '',
            question: '',
            recruitment: ''
        })
    }).catch(err => {
        console.log(err)
    })

})

//我的足迹
router.get("/history", function (req, res) {
    if (req.session.user) {
        res.render("topic/history.html", {
            user: req.session.user
        })
    } else {
        res.send("请先登录，登录后才可查看历史记录")
    }
})
//我的文章
router.get("/myshare", function (req, res, next) {
    if (!req.session.user) {
        res.send("请先登录")
        return;
    }
    Share.find({ author: req.session.user.nickname }, function (err, docs) {
        if (err) return next(err)

        res.render("topic/my.html", {
            user: req.session.user,
            mydata: docs.reverse(),
            cshare: "active",
            cquestion: "",
            crecruitment: ""
        })
    })
})


router.get("/myquestion", function (req, res, next) {
    if (!req.session.user) {
        res.send("请先登录")
        return;
    }
    Question.find({ author: req.session.user.nickname }, function (err, docs) {
        if (err) return next(err)

        res.render("topic/my.html", {
            user: req.session.user,
            mydata: docs.reverse(),
            cshare: "",
            cquestion: "active",
            crecruitment: ""
        })
    })
})

router.get("/myrecruitment", function (req, res, next) {
    if (!req.session.user) {
        res.send("请先登录")
        return;
    }
    Recruitment.find({ author: req.session.user.nickname }, function (err, docs) {
        if (err) return next(err)

        res.render("topic/my.html", {
            user: req.session.user,
            mydata: docs.reverse(),
            cshare: "",
            cquestion: "",
            crecruitment: "active"
        })
    })
})
//文章编辑
router.get("/edit/share", function (req, res, next) {
    if (!req.session.user) return res.send("请先登录")
    var id = req.query.id.slice(1, -1);
    Share.findById(id, function (err, doc) {
        if (err) return next(err)
        res.render("topic/edit.html", {
            user: req.session.user,
            editContent: doc,
            index: 0,
            id:id
        })
    })

})

router.get("/edit/question", function (req, res, next) {
    if (!req.session.user) return res.send("请先登录")
    var id = req.query.id.slice(1, -1);
    Question.findById(id, function (err, doc) {
        if (err) return next(err)
        res.render("topic/edit.html", {
            user: req.session.user,
            editContent: doc,
            index: 1,
            id:id
        })
    })

})


router.get("/edit/recruitment", function (req, res, next) {
    if (!req.session.user) return res.send("请先登录")
    var id = req.query.id.slice(1, -1);
    Recruitment.findById(id, function (err, doc) {
        if (err) return next(err)
        res.render("topic/edit.html", {
            user: req.session.user,
            editContent: doc,
            index: 2,
            id:id
        })
    })

})
//文章删除
router.get("/delete", function (req, res, next) {
    var id = req.query.id.slice(1, -1);
    var type = req.query.type;
    switch (type) {
        case "share":
            Share.findOneAndDelete({ _id: id }, function (err) {
                if (err) return next(err)
            })
            res.send("删除成功")
            break;
        case "question":
            Question.findOneAndDelete({ _id: id }, function (err) {
                if (err) return next(err)
            })
            res.send("删除成功")
            break;
        case "recruitment":
            Recruitment.findOneAndDelete({ _id: id }, function (err) {
                if (err) return next(err)
            })
            res.send("删除成功")
            break;
    }
})
module.exports = router